<?php
namespace app\api\controller\service;

use app\common\controller\Api;
use EasyWeChat\Factory;
use think\Db;
use think\Loader;
/**
 * 首页接口
 */
class Skill extends Api
{
    protected $noNeedLogin = ['nearSkill','searchSkill','skillInfo','getSampleSkill'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

    }

    /**
     * 生成服务人员二维码
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function getQrCode()
    {
        $info = \app\api\model\service\ProjectConfigure::getProjectConfig();

        $uid = $this->auth->id;
        $config = [
            'app_id' => $info['skillappid'],
            'secret' => $info['skillsecret'],

            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'response_type' => 'array',

            'log' => [
                'level' => 'debug',
                'file' => __DIR__.'/wechat.log',
            ],
        ];

        $app = Factory::miniProgram($config);
        $response = $app->app_code->getQrCode('/service/login/login?pid='.$uid);
        // return $response;

        // 保存小程序码到文件
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->saveAs(ROOT_PATH.'public/uploads/skill_qrcode',$uid.'.png');
            
            $filename = 'uploads/skill_qrcode/'.$filename;
            
            $res = Db::name('service_skill')->where('user_id',$uid)->update(['qrcode'=>$filename]);
            $this->success(__('获取成功'), 'https://'.$_SERVER['SERVER_NAME'].'/'.$filename);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 申请服务人员,完善资料
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function apply()
    {
        $uid = $this->auth->id;
        $userInfo = model('app\api\model\service\UserInfo')->where(['user_id'=>$uid])->field('id,is_skill')->find();
        $info = model('app\api\model\service\ApplySkill')->where(['user_id'=>$uid])->find();
        $post = input('post.','','trim,strip_tags,htmlspecialchars,xss_clean');
        $type = input('type','');
        $applySkill = new \app\api\model\service\ApplySkill();
        $post['user_id'] = $uid;
        $post['updatetime'] = time();
        if(in_array($type,['add','edit']))
        {
            $validate = Loader::validate('service.ApplySkill');
            if(!$validate->scene($type)->check($post)){
                $this->error($validate->getError());
            }
        }
        if($type == 'add')
        {
            $userInfo['is_skill'] == 1 && $this->error('请勿重复申请');
            unset($post['type']);
            $applySkill->data($post)->save();
            $this->success('申请已提交,等待审核');
        }elseif($type == 'edit') {
            unset($post['type']);
            $post['state'] = 0;
            $applySkill->allowField(true)->save($post,['id'=>$info['id']]);
            $this->success('申请已提交,等待审核');
        }elseif ($type == 'perfect') {
            $post['state'] = 0;
            $post['applytype'] = 1;
            $applySkill->allowField(true)->save($post,['id'=>$info['id']]);
            $this->success('申请已提交,等待审核');
        }
        if($info){
            $info['skillCateName'] = \app\api\model\service\SkillCate::getName($info['skill_cate_id']);
        }
        $this->success('信息返回成功',$info);
    }

    public function addGoodsTime()
    {
        $id = input('id/d','');
        $ids = input('ids','');
        $order = \app\api\model\service\Order::where(['id'=>$id,'state'=>['in',[2,3,4,5]]])->field('id,skill_id,actendtime')->find();
        $addIds = explode(',',$ids);
        $totalCostSeconds = 0;
        $payprice = 0;
        foreach ($addIds as $val)
        {
            $info = \app\api\model\service\GoodsAdd::where(['id'=>$val,'state'=>1])->find();
            if(!$info){
                $this->error('当前有附加项目无法使用,请刷新后重试');
            }
            $totalCostSeconds+=$info['cost_seconds'];
            $payprice+=$info['price'];
        }
        if($order)
        {
            $endTime = $order['actendtime']+$totalCostSeconds;
            $exist = \app\api\model\service\SkillTime::where(['skill_id'=>$order['skill_id'],'state'=>['>',0],'starttime'=>['between',[$order['actendtime'],$endTime]]])->value('id');
            $exist && $this->error('当前服务者已被预约,暂时无法接单');
        }
        $this->success('信息返回成功',['payprice'=>$payprice,'totalCostSeconds'=>$totalCostSeconds]);
    }



    /**
     * 首页附近服务人员
     * @return void
     */
    public function nearSkill()
    {
        $get = input('get.','','trim,strip_tags');
        $get['limit'] = 10;
        !$get['city'] && $this->error('城市信息缺失');
        (!$get['lng'] || !$get['lat']) && $this->error('定位信息异常');
        $nearSkill = \app\api\model\service\Skill::nearSkill($get);
        // return json($nearSkill);
        
        if($nearSkill)
        {
            foreach ($nearSkill as &$value)
            {
                $value['skillCate'] = model('app\api\model\service\Category')->where(['id'=>['in',$value['goods_ids']]])->column('name');
                $value['skillTime'] = \app\api\model\service\SkillTime::getSkillTime($value['id']);
                $value['good_comment_percent'] =  \app\api\model\service\Comment::skillGoodPercent(['skill_id'=>$value['id']]);
            }
        }
        $this->success('信息返回成功',$nearSkill);
    }

    /**
     * 查询服务人员列表
     * @return void
     */
    public function searchSkill()
    {
        $get = input('get.','','trim,strip_tags');
        $get['limit'] = 10;
        $get['page'] = input('page/d',1);
        !$get['city'] && $this->error('城市信息缺失');
        (!$get['lng'] || !$get['lat']) && $this->error('定位信息异常');
        $list = \app\api\model\service\Skill::searchSkill($get);
        // return json($list);
        if($list)
        {
            foreach ($list as &$value)
            {
                $value['shopname'] = $value['shop_id']?\app\api\model\service\Shop::getName($value['shop_id']):'';
                $value['skillTime'] = \app\api\model\service\SkillTime::getSkillTime($value['id']);
                $value['skillCate'] = \app\api\model\service\SkillCate::where('id',$value['skill_cate_id'])->value('name');
                $value['commentCount'] = \app\api\model\service\Comment::getCount(['skill_id'=>$value['id'],'state'=>1]);
                $value['good_comment_percent'] =  \app\api\model\service\Comment::skillGoodPercent(['skill_id'=>$value['id']]);
            }
        }
        $this->success('信息返回成功',$list);
    }

    /**
     * 获取服务人员详情
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function skillInfo()
    {
        $uid = $this->auth->isLogin()?$this->auth->id:'';
        $id = input('id/d','');
        $lng = input('lng');
        $lat = input('lat');
        $info = \app\api\model\service\Skill::getInfo($id,$uid);
        // return json_encode($info);
        !$info && $this->error('服务人员信息异常');
        $info['distance'] = \addons\service\library\Common::distance($lng,$lat,$info['lng'],$info['lat']);
        $info['skillTime'] = \app\api\model\service\SkillTime::getSkillTime($info['id']);
        $info['good_comment_percent'] = \app\api\model\service\Comment::skillGoodPercent(['skill_id'=>$info['id']]);
        $this->success('信息返回成功',$info);
    }


    /**
     * 加入商户
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function joinShop()
    {
        $uid = $this->auth->id;
        $skill = \app\api\model\service\Skill::getSkillShop($uid);
        $data['skill'] = $skill;
        $data['joinShop'] = \app\api\model\service\JoinShop::where(['skill_id'=>$skill['id']])->order('id desc')->find();
        $type = input('type','','trim,strip_tags');
        if(is_numeric($type)){
            $skill['shop_id'] && $this->error('请勿重复申请');
            $info = \app\api\model\service\JoinShop::where(['skill_id'=>$skill['id'],'state'=>['>=',0]])->field('id,code,shop_name,state')->order('id desc')->find();
            if($info && $info['state']>=0){
            //   $this->error('请勿重复申请');
               /*修改逻辑检测到就删除 作者:wtj 2025-05-19*/ 
               \app\api\model\service\JoinShop::where('id',$info['id'])->delete();
            } 
            if($type)
            {
                $code = input('code/s','','trim,strip_tags');
                $shop = \app\api\model\service\Shop::where(['code'=>$code,'state'=>1])->field('id,name,code')->find();
            }else{
                $id = input('id/d','','trim,strip_tags');
                $shop = \app\api\model\service\Shop::where(['id'=>$id,'state'=>1])->field('id,name,code')->find();
            }
            !$shop && $this->error('所选商家信息异常');
            \app\api\model\service\JoinShop::create(['skill_id'=>$skill['id'],'skill_name'=>$skill['name'],'shop_id'=>$shop['id'],'code'=>$shop['code'],'shop_name'=>$shop['name']]);
            $this->success('申请已提交,等待审核');
        }
        $this->success('信息返回成功',$data);
    }



    public function skillIndex()
    {
        $uid = $this->auth->id;
        $skill = \app\api\model\service\Skill::where(['user_id'=>$uid])->field('id,shop_id,code,ensure_price,name,sex,image,goods_ids,skill_cate_id')->find();
        !$skill && $this->error('非服务者无法访问');
        $skill['skillCateName'] = \app\api\model\service\SkillCate::getName($skill['skill_cate_id']);
        $data['userInfo'] = \app\api\model\service\UserInfo::where(['user_id'=>$uid])->field('money,shop_money')->find();
        $data['skill'] = $skill;
        // $data['goodsCount'] = count(explode(',',$skill['goods_ids']));
        /*修改为计算已经接单正在进行中未完成的的数量*/
        
        // $goodsList = $skill['shop_id'] == 0 ? \app\api\model\service\Goods::getSkillGoods($skill['goods_ids']) : \app\api\model\service\Goods::getShopPlatformGoods($skill['goods_ids'],$uid);
        
        // return json(\app\api\model\service\Goods::getShopPlatformGoods($skill['goods_ids'],$uid));
        // $data['goodsCount'] = count( \app\api\model\service\Goods::getShopPlatformGoods($skill['goods_ids'],$uid) );
        
        $data['goodsCount'] = \app\api\model\service\Order::where(['user_id'=>$uid])->whereIn('status',[2,3,4,5])->count();
        $this->success('服务者信息返回成功',$data);
    }

    public function skillHome()
    {
        $uid = $this->auth->id;
        $skillId = input('skill_id/d','')?:\app\api\model\service\Skill::where(['user_id'=>$uid])->value('id');
        !$skillId && $this->error('非服务者无法访问');
        $data['orderCount'] = \app\api\model\service\Order::getSkillOrderCount(['skill_id'=>$skillId,'status'=>['in',[2,3,4,5]],'is_service'=>['in',[0,-1]]]);
        $this->success('信息返回成功',$data);
    }

    /**
     * 服务者获取时间更新时间状态
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function skillTime()
    {
        $uid = $this->auth->id;
        $skillId = input('skill_id/d','');
        $skillId = $skillId?$skillId:\app\api\model\service\Skill::where(['user_id'=>$uid])->value('id');
        !$skillId && $this->error('非服务者无法访问');
        $timetype = input('timetype/d',0);
        $ids = input('ids','');
        $list = \app\api\model\service\SkillTime::where(['timetype'=>$timetype,'skill_id'=>$skillId])->field('id,timetype,number,state,starttime,endtime')->select();
        $type = input('type','');
        if($type)
        {

            $re = \app\api\model\service\SkillTime::updateTime($ids,$skillId,$type);
            !$re && $this->error('更新失败');
            $this->success('时间状态已更改');
        }
        $this->success('信息返回成功',$list);
    }



    /**
     * 更新服务者部分信息
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function updateSkillInfo()
    {
        $uid = $this->auth->id;
        $skillId = input('skill_id/d','');
        $skillId = $skillId?$skillId:\app\api\model\service\Skill::where(['user_id'=>$uid])->value('id');
        $skill = \app\api\model\service\Skill::where(['id'=>$skillId])->field('id,shop_id,province,city,district,address,lng,lat,is_rest,is_train,code,percent')->find();
        $type = input('type','');
        if($type == 'update')
        {
            $post = input('post.','','trim,strip_tags,htmlspecialchars,xss_clean');
            if($skill['shop_id']){
                $max_percent = \app\api\model\service\Shop::where(['id'=>$skill['shop_id']])->value('percent');
            }else{
                $max_percent = $skill['percent'];
            }
            if(isset($post['percent']) && $post['percent'] > $max_percent) $this->error('订单抽成最大设置为'.$max_percent);
            
            model('app\api\model\service\Skill')->allowField('province,city,district,address,lng,lat,is_rest,percent')->save($post,['id'=>$skillId]);
            $this->success('信息已更新');
        }
        $this->success('信息返回成功',$skill);
    }

    public function getSampleSkill()
    {
        $id = input('id/d','');
        $skill = \app\api\model\service\Skill::where(['id'=>$id])->field('id,mobile,code,name,idcard,health_image,certificate_image,image')->find();
        $skill['idcard'] = substr_replace($skill['idcard'],'******',6,6);
        $this->success('信息返回成功',$skill);
    }


}